package com.zcah.system.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zcah.system.dao.JwtuserDao;
import com.zcah.system.domain.JwtuserDO;
import com.zcah.system.util.JWTUtils;

@Service
public class UserRealm extends AuthorizingRealm{
	private static final Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);

	@Autowired
	private JwtuserDao jwtuserDao;

	/**
	 * 大坑！，必须重写此方法，不然Shiro会报错
	 */
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof JWTToken;
	}

	/**
	 * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的,
	 * 这里省略了permission，直接使用role进行权限管理
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		// TODO 需要加缓存
		String username = JWTUtils.getUsername(principals.toString());
		JwtuserDO user = jwtuserDao.getUser(username);
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRole(user.getRole());
		// 使用角色直接区分权限，不使用rbac
//		Set<String> permission = new HashSet<>(Arrays.asList(user.getPermission().split(",")));
//		simpleAuthorizationInfo.addStringPermissions(permission);
		return simpleAuthorizationInfo;
	}

	/**
	 * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
		
		// TODO  每次认证鉴权都需要访问数据库，需要加缓存
		String token = (String) auth.getCredentials();
		// 解密获得username，用于和数据库进行对比
		String username = JWTUtils.getUsername(token);
		if (username == null) {
			throw new AuthenticationException("token invalid");
		}

		JwtuserDO user = jwtuserDao.getUser(username);
		if (user == null) {
			throw new AuthenticationException("User didn't existed!");
		}

		if (!JWTUtils.verify(token, username, user.getPassword())) {
			throw new AuthenticationException("Username or password error");
		}

		return new SimpleAuthenticationInfo(token, token, "user_realm");
	}
}
